import {Directive, ElementRef, HostListener, EventEmitter, Input, Output} from '@angular/core';


@Directive({
  selector: '[appTouch]'
})
export class TouchDirective {
  //滑动方向
  private direction: any;

  constructor(private el: ElementRef) {
  }

  @Output() touchDirection = new EventEmitter();
  @Input() isSelect:any;
  ngOnInit() {
    console.log(this.isSelect)
  }

  // @HostListener('click', ['$event'])
  // onClick() {
  //   console.log('点击了');
  // }

  //触摸手指数
  private touchNumber: number;
  //触摸开始手指位置
  private touchStartPositionX: number;
  private touchStartPositionY: number;

  //触摸开始
  @HostListener('touchstart', ['$event'])
  public moveStart(event) {
    // this.touchDirection = '哈哈';
    // console.log(this.touchDirection);

    // console.log('滑动了');
    // console.log(event);
    // console.log(event.targetTouches[0].pageX);
    //取触摸手指数
    this.touchNumber = event.changedTouches.length;
    //单指操作
    if (this.touchNumber == 1) {
      // 获取手指开始位置
      this.touchStartPositionX = event.targetTouches[0].pageX;
      this.touchStartPositionY = event.targetTouches[0].pageY;
      // console.log('开始手指x位置:' + this.touchStartPositionX);
      // console.log('开始手指y位置:' + this.touchStartPositionY);
    }
  }

  //触摸移动手指位置
  private touchIngPositionX: number;
  private touchIngPositionY: number;

  //触摸移动
  @HostListener('touchmove', ['$event'])
  public moveing(event) {
    // console.log('滑动中');
    // console.log(event);
    //  移动中的手指位置
    this.touchIngPositionX = event.targetTouches[0].pageX;
    this.touchIngPositionY = event.targetTouches[0].pageY;
    // console.log('移动手指位置X:'+this.touchIngPositionX);
    // console.log('移动手指位置Y:'+this.touchIngPositionY);
    let distanceX = this.touchStartPositionX - this.touchIngPositionX;
    let distanceY = this.touchStartPositionY - this.touchIngPositionY;


    this.judgeDirection(distanceX, distanceY);
  }

//滑动距离
//   private distanceX = this.touchStartPositionX - this.touchIngPositionX;

  //判断滑动方向
  public judgeDirection(distanceX, distanceY) {
    // console.log('位置' + distanceX);
    if (Math.abs(distanceX) < 10 && Math.abs(distanceY) < 10) {
      this.direction = 'to';
    } else {
      if (Math.abs(distanceX) > Math.abs(distanceY) && distanceX > 0) {
        console.log('往左滑动');
        this.direction = 'touchLeft';
      } else if (Math.abs(distanceX) > Math.abs(distanceY) && distanceX < 0) {
        console.log('往右滑动');
        this.direction = 'touchRight';
      } else if (Math.abs(distanceX) < Math.abs(distanceY) && distanceY < 0) {
        console.log('向下滑动');
        this.direction = 'touchBottom';
      } else if (Math.abs(distanceX) < Math.abs(distanceY) && distanceY > 0) {
        console.log('向上滑动');
        this.direction = 'touchTop';
      }
    }

  }

  //滑动结束
  @HostListener('touchend', ['$event'])
  public moveEnd(event) {
    // console.log('触摸结束');
    // console.log(event);
    this.touchDirection.emit(this.direction);

  }


}
